package com.meteor.downloader.videodownloader.downloading

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.liulishuo.okdownload.DownloadSerialQueue
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.core.cause.ResumeFailedCause
import com.liulishuo.okdownload.core.listener.DownloadListener3
import com.meteor.downloader.videodownloader.mdmdata.DataDownloadingMdm
import com.meteor.downloader.videodownloader.utils.value.ParamsMdmUtils
import com.meteor.downloader.videodownloader.utils.value.ParamsMdmUtils.mDownloadingMdmList
import java.io.File
import kotlin.math.floor

class MdmDownloadingService : Service() {
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        mDownloadingMdmList.let {
            if (it.isNotEmpty()) {
                for (i in it.size - 1 downTo 0) {
                    val data = it[i]
                    if (data.mCancelMdm) {
                        it.removeAt(i)
                    } else {
                        if ((data.mTaskMdm == null && data.mProgressMdm == 0) || data.mErrorMdm) {
                            val task = getTIDownloadTask(
                                data.videoUrlMdm,
                                ParamsMdmUtils.mSaveFileMdm.path,
                                getFileName(data)
                            )
                            data.mErrorMdm = false
                            data.mTaskMdm = task
                            data.mQueueVideoMdm = DownloadSerialQueue(getVideoListener(i))
                            data.mQueueVideoMdm?.enqueue(task)
                        } else {
                            if (data.mProgressMdm >= 100) {
                                it.removeAt(i)
                            }
                        }
                    }
                }
            }
        }
        return START_STICKY
    }


    private fun getTIDownloadTask(url: String, parent: String, name: String): DownloadTask {
        return DownloadTask.Builder(
            url, parent, name
        ).setFilenameFromResponse(false).setConnectionCount(1).setPassIfAlreadyCompleted(false)
            .setMinIntervalMillisCallbackProcess(1400).setPreAllocateLength(false)
            .setConnectionCount(1).build()
    }

    private fun getFileName(data: DataDownloadingMdm): String {
        val newName = when (data.videoMediaTypeMdm) {
            "image", "photo" -> {
                "Image_${System.currentTimeMillis()}.${data.videoExtensionMdm}"
            }

            "audio" -> {
                "Audio_${System.currentTimeMillis()}.${data.videoExtensionMdm}"
            }

            "video" -> {
                "Video_${System.currentTimeMillis()}.${data.videoExtensionMdm}"
            }

            else -> {
                "Video_${System.currentTimeMillis()}.mp4"
            }
        }
        val newFile = File(ParamsMdmUtils.mSaveFileMdm, newName)
        data.mCacheFileMdm = newFile
        data.mFileNameMdm = newName
        return newName
    }

    private fun getVideoListener(position: Int): DownloadListener3 {
        val data = mDownloadingMdmList[position]
        return object : DownloadListener3() {
            override fun retry(task: DownloadTask, cause: ResumeFailedCause) {

            }

            override fun connected(
                task: DownloadTask, blockCount: Int, currentOffset: Long, totalLength: Long
            ) {
            }

            override fun progress(task: DownloadTask, currentOffset: Long, totalLength: Long) {
                if (totalLength == 0L) {
                    data.mTotalSizeMdm = currentOffset
                    data.mSizeVideoMdm = currentOffset
                    if (data.mProgressMdm < 86) {
                        data.mProgressMdm += 1
                    }
                    data.mVideoDownloadingListener?.progress()
                    return
                }
                var progress = floor((currentOffset * 1.0 / totalLength) * 100).toInt()
                if (progress >= 100 || progress < 0) {
                    progress = 100
                }
                data.mTotalSizeMdm = totalLength
                data.mSizeVideoMdm = currentOffset
                data.mProgressMdm = progress
                data.mVideoDownloadingListener?.progress()
            }

            override fun started(task: DownloadTask) {
            }

            override fun completed(task: DownloadTask) {
                data.mTaskMdm = null
                data.mQueueVideoMdm = null
                data.mProgressMdm = 100
                mDownloadingMdmList.remove(data)
                data.mVideoDownloadingListener?.complete()
//                CoroutineScope(Dispatchers.IO).launch {
//                    FileUtils.loadVideoBitmapMdm(
//                        MdmDealApplication.mMdmContext,
//                        data.imageShowSnap
//                    ) {
//                        data.imageBitmap = it
//                        MdmClueDownload.getMdmClueShowTwo(
//                            MdmDealApplication.mMdmContext,
//                            true,
//                            data
//                        )
//                    }
//                }
            }

            override fun canceled(task: DownloadTask) {
                if (data.mVideoPauseMdm) return
                try {
                    data.mCacheFileMdm?.delete()
                } catch (_: Exception) {
                }
                mDownloadingMdmList.remove(data)
            }

            override fun error(task: DownloadTask, e: java.lang.Exception) {
                data.mErrorMdm = false
            }

            override fun warn(task: DownloadTask) {

            }

        }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
}